package cn.wowjoy.office.materialmanage.inventory;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.app.Instrumentation;
import android.arch.lifecycle.Observer;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;

import java.util.List;

import cn.wowjoy.office.R;
import cn.wowjoy.office.baselivedata.appbase.LiveDataWrapper;
import cn.wowjoy.office.baselivedata.appbase.NewBaseActivity;
import cn.wowjoy.office.common.customview.MaskFramLayout;
import cn.wowjoy.office.common.decoration.SimpleItemDecoration;
import cn.wowjoy.office.common.widget.CommonDialog;
import cn.wowjoy.office.common.widget.CreateDialog;
import cn.wowjoy.office.common.widget.MDialog;
import cn.wowjoy.office.data.mock.PopuModel;
import cn.wowjoy.office.data.remote.ResultEmpty;
import cn.wowjoy.office.data.response.InventoryResponse;
import cn.wowjoy.office.databinding.ActivityMaterialInventoryBinding;
import cn.wowjoy.office.utils.ToastUtil;

@Route(path = "/materialmanage/inventory/materialinventory")
public class MaterialInventoryActivity extends NewBaseActivity<ActivityMaterialInventoryBinding,MaterialInventoryViewModel> implements View.OnClickListener {

    private int initHeight;
    private boolean isOpen = false;
    private MDialog waitDialog;
    private boolean isMenuFailed = false;
    private boolean isHasStockFailed = false;
    private boolean isCheckStockFailed = false;
    private String key;
    private CommonDialog lockDialog;
    private String storageName;
    private String storageCode;


    @Override
    protected Class getViewModel() {
        return MaterialInventoryViewModel.class;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_material_inventory;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        binding.setViewmodel(viewModel);
        initView();
        initMenu();
        initRV();
        initObsever();
        viewModel.getStock();
        viewModel.getStatus();

    }
    private void clearDialog(){
        if (waitDialog != null ){
            waitDialog.dismiss();
            waitDialog = null;
        }
    }

    private void showLockDialog(){
        if (null == lockDialog)
            lockDialog = new CommonDialog.Builder()
                    .setTitle("锁定")
                    .setKey("是否确定锁定？",0xff333333,13.33f)
                    .setContent("                   是否确定锁定？\n                   当前仓库："+ storageName)
                    .setContentGravity(Gravity.CENTER|Gravity.LEFT)
                    .setCancelBtn("取消", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            lockDialog.dismiss();
                        }
                    })
                    .setConfirmBtn("确定", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            lockDialog.dismiss();
                            viewModel.lockStock();
                        }
                    })
                    .create();
        lockDialog.show(getSupportFragmentManager(),null);
    }


    private void initMenu(){
        binding.menuFl.setBgAlapht(77);
        binding.meunRecyclerview.setLayoutManager(new LinearLayoutManager(this));
        binding.meunRecyclerview.setAdapter(viewModel.statusMenu);
        binding.meunRecyclerview.addItemDecoration(new SimpleItemDecoration(this,SimpleItemDecoration.VERTICAL_LIST));
        binding.menuFl.setDimissListener(new MaskFramLayout.DimissListener() {
            @Override
            public void onDismiss() {
                closeFolder();
                binding.menu.setSelected(isOpen);
            }
        });

        binding.menu.setSelected(false);
        binding.menu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                removeErrorview();
                if (isOpen){
                    closeFolder();

                } else {
                    openFolder();
                }
                binding.menu.setSelected(isOpen);

            }
        });
    }

    private void initRV(){
        binding.emptyView.emptyContent.setText("可搜索盘点单号");
        binding.recyclerView.setEmptyView(binding.emptyView.getRoot());
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        binding.recyclerView.addItemDecoration(new SimpleItemDecoration(this,SimpleItemDecoration.VERTICAL_LIST));
        binding.searchEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                hideSoftInput();
                if (isOpen){
                    closeFolder();
                    binding.menu.setSelected(isOpen);
                }
                key = binding.searchEditText.getText().toString().trim();
                viewModel.setKeyWord(key);
                viewModel.getInventory(true);
                return true;
            }
        });
        binding.searchEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(binding.searchEditText.getText().toString())){
                    binding.delete.setVisibility(View.VISIBLE);

                } else {
                    binding.delete.setVisibility(View.GONE);
                    key = null;
                }

            }
        });
        binding.delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.searchEditText.setText("");
                binding.delete.setVisibility(View.GONE);
                key = null;
                viewModel.setKeyWord(key);
            }
        });

    }

    private boolean ifFcousFliding = false;
    private boolean isHasFlid = false;
    private void initView(){
        binding.back.setOnClickListener(this);
        lockAdd(false);
//        binding.lockStockTv.setEnabled(true);
//        binding.lockStockMask.setVisibility(View.VISIBLE);
//        binding.addReportTv.setEnabled(false);
//        binding.addReportMask.setVisibility(View.GONE);
        binding.lockStockTv.setOnClickListener(this);
        binding.addReportTv.setOnClickListener(this);
        binding.searchEditText.setOnClickListener(this);
        binding.appbar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (verticalOffset < 0){
                    isHasFlid = true;
                } else {
                    isHasFlid = false;
                }
            }
        });
        binding.searchEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus && !ifFcousFliding){
                    mockFliding();
                } else {
                    ifFcousFliding = false;
                }
            }
        });

    }


    /**
     * 模拟滑动事件
     */
    private void mockFliding(){
        if (!isHasFlid)
            new Thread(new Runnable() {
            @Override
            public void run() {
                Instrumentation inst = new Instrumentation();
                float x = 45.0f;
                float y = 200.0f;
                long dowTime = SystemClock.uptimeMillis();
                inst.sendPointerSync(MotionEvent.obtain(dowTime,dowTime,
                        MotionEvent.ACTION_DOWN, x, y,0));
                inst.sendPointerSync(MotionEvent.obtain(dowTime,dowTime,
                        MotionEvent.ACTION_MOVE, x, y - 20,0));
                inst.sendPointerSync(MotionEvent.obtain(dowTime,dowTime+20,
                        MotionEvent.ACTION_MOVE, x, y - 30,0));
                inst.sendPointerSync(MotionEvent.obtain(dowTime,dowTime+30,
                        MotionEvent.ACTION_MOVE, x, y - 40,0));
                inst.sendPointerSync(MotionEvent.obtain(dowTime,dowTime+40,
                        MotionEvent.ACTION_MOVE, x, y - 50,0));
                inst.sendPointerSync(MotionEvent.obtain(dowTime,dowTime+40,
                        MotionEvent.ACTION_UP, x, y - 60,0));
                ifFcousFliding = true;
            }
        }).start();

    }

    private void lockAdd(boolean isChecked){
        binding.lockStockTv.setEnabled(!isChecked);
        binding.lockStockMask.setVisibility(!isChecked ? View.GONE : View.VISIBLE);
        binding.addReportTv.setEnabled(isChecked);
        binding.addReportMask.setVisibility(isChecked ? View.GONE : View.VISIBLE);
    }

    private void initObsever(){
        viewModel.stockMenu.observe(this, new Observer<LiveDataWrapper<List<PopuModel>>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<List<PopuModel>> listLiveDataWrapper) {
                switch (listLiveDataWrapper.status){
                    case LOADING:
                        clearDialog();
                        waitDialog = CreateDialog.waitingDialog(MaterialInventoryActivity.this);
                        break;
                    case SUCCESS:
                        waitDialog.dismiss();
                        isHasStockFailed = false;
                        if (!listLiveDataWrapper.data.isEmpty()){
                            storageName = listLiveDataWrapper.data.get(0).getName();
                            storageCode = listLiveDataWrapper.data.get(0).getStorageCode();
                        }
                        break;
                    case ERROR:
                        waitDialog.dismiss();
                        isHasStockFailed = true;
                        handleException(listLiveDataWrapper.error,true);
                        break;
                }
            }
        });
        viewModel.isChecked.observe(this, new Observer<LiveDataWrapper<String>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<String> stringLiveDataWrapper) {
                switch (stringLiveDataWrapper.status){
                    case LOADING:
                        clearDialog();
                        waitDialog = CreateDialog.waitingDialog(MaterialInventoryActivity.this);
                        break;
                    case SUCCESS:
                        waitDialog.dismiss();
                        isCheckStockFailed = false;
                        if (TextUtils.equals("y",stringLiveDataWrapper.data)){
                            lockAdd(false);
                        } else {
                            lockAdd(true);
                        }
                        break;
                    case ERROR:
                        waitDialog.dismiss();
                        isCheckStockFailed = true;
                        handleException(stringLiveDataWrapper.error,true);
                        break;
                }
            }
        });
        viewModel.menus.observe(this, new Observer<LiveDataWrapper<List<PopuModel>>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<List<PopuModel>> listLiveDataWrapper) {
                switch (listLiveDataWrapper.status){
                    case LOADING:
                        clearDialog();
                        waitDialog = CreateDialog.waitingDialog(MaterialInventoryActivity.this);
                        break;
                    case SUCCESS:
                        waitDialog.dismiss();
                        isMenuFailed = false;
                        initHeight= getResources().getDimensionPixelSize(R.dimen.height2)*listLiveDataWrapper.data.size();
                        break;
                    case ERROR:
                        waitDialog.dismiss();
                        isMenuFailed = true;
                        handleException(listLiveDataWrapper.error,false);
                        break;
                }
            }
        });
        viewModel.liveData.observe(this, new Observer<LiveDataWrapper<List<InventoryResponse>>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<List<InventoryResponse>> listLiveDataWrapper) {
                switch (listLiveDataWrapper.status){
                    case LOADING:
                        clearDialog();
                        waitDialog = CreateDialog.waitingDialog(MaterialInventoryActivity.this);
                        break;
                    case SUCCESS:
                        waitDialog.dismiss();
                        break;
                    case ERROR:
                        waitDialog.dismiss();
                        handleException(listLiveDataWrapper.error,true);
                        break;
                }
            }
        });
        viewModel.meun.observe(this, new Observer<PopuModel>() {
            @Override
            public void onChanged(@Nullable PopuModel popuModel) {
                setFloder(popuModel);
                closeFolder();
            }
        });
        viewModel.lockStock.observe(this, new Observer<LiveDataWrapper<ResultEmpty>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<ResultEmpty> resultEmptyLiveDataWrapper) {
                switch (resultEmptyLiveDataWrapper.status){
                    case LOADING:

                        break;
                    case SUCCESS:
                        lockAdd(true);
//                        binding.lockStockTv.setEnabled(false);
//                        binding.addReportTv.setEnabled(true);
                        ToastUtil.toastImage(MaterialInventoryActivity.this,"锁定成功",0);
                        break;
                    case ERROR:

                        handleException(resultEmptyLiveDataWrapper.error,false);
                        break;
                }

            }
        });
    }

    @Override
    protected ViewGroup getErrorViewRoot() {
        return binding.content;
    }

    @Override
    protected void refreshError() {
        super.refreshError();
        if (isHasStockFailed){
            viewModel.getStock();
        } else if(isCheckStockFailed){
            viewModel.isChecked();
        } else if (isMenuFailed){
            viewModel.getStatus();
        } else {
            viewModel.getInventory(true);
        }
    }

    /**
     * 弹出文件夹列表
     */
    protected void openFolder() {

        hideSoftInput();
        if (!isOpen) {
            binding.menuFl.setVisibility(View.VISIBLE);
            if (binding.meunRecyclerview.getHeight() != 0){
                initHeight = binding.meunRecyclerview.getHeight();
            }
            ObjectAnimator animator = ObjectAnimator.ofFloat(binding.meunRecyclerview, "translationY",
                    -initHeight, 0).setDuration(300);
            animator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationStart(Animator animation) {
                    super.onAnimationStart(animation);
                    binding.meunRecyclerview.setVisibility(View.VISIBLE);
                }
            });
            animator.start();
            isOpen = true;
        }
    }
    protected void setFloder(PopuModel popuModel){
        binding.menu.setText(popuModel.getName());
    }


    /**
     * 收起文件夹列表
     */
    protected void closeFolder() {

        hideSoftInput();
        if (isOpen) {
            if (binding.meunRecyclerview.getHeight() != 0){
                initHeight = binding.meunRecyclerview.getHeight();
            }
            ObjectAnimator animator = ObjectAnimator.ofFloat(binding.meunRecyclerview, "translationY",
                    0,-initHeight).setDuration(300);
            animator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    super.onAnimationEnd(animation);
                    binding.meunRecyclerview.setVisibility(View.GONE);
                    binding.menuFl.setVisibility(View.GONE);
                }
            });
            animator.start();
            isOpen = false;
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.back:
                onBackPressed();
                break;
            case R.id.lock_stock_tv:
                showLockDialog();
                break;
            case R.id.add_report_tv:
                ARouter.getInstance().build("/materialmanage/inventoryRecord/inventoryRecord")
                        .withString("storageCode",storageCode)
                        .navigation();
                break;
            case R.id.search_edit_text:
                mockFliding();
                break;

        }
    }
}
